<script setup>
import productionBoard1v2 from '@/views/visual/modules/productionBoard1v2.vue'
import { getAllMachine } from '@/api/pannel/machinePannel.js'
import MqttServer from '@/socket/mqtt'
import { computed, onMounted, onUnmounted } from 'vue'
let mqttServer = null
const socket = inject('socket')
const machineList = ref([])

const props = defineProps({
  params: {
    type: Object,
    default: () => ({})
  }
})

const list = computed(() => {
  const item = [
    {
      value: 0,
      status: '设备',
      color: '#ccc',
      border: '1px solid #ccc'
    },
    {
      value: 0,
      status: '开机',
      color: '#9acd31',
      border: '1px solid #9acd31'
    },
    {
      value: 0,
      status: '停机',
      color: 'red',
      border: '1px solid red'
    }
  ]
  for (let i = 0; i < machineList.value.length; i++) {
    if (machineList.value[i].oldValue === 0 && machineList.value[i].oldValue === 0) {
      item[2].value++
    } else {
      item[1].value++
    }
  }
  item[0].value = machineList.value.length
  return item
})
const loadData = async () => {
  const { machines } = await getAllMachine({ ...props.params, key: 'topic1' })
  const topics = []
  machineList.value = machines.map(item => {
    item.type = item.zt === '未开工' ? 'red' : item.gxmc.includes('调机') ? 'blur' : 'green'
    if (item.topic) {
      item.sj = 0
      item.oldValue = 0
      item.showTipicIcon = false
      item.runTime = 0
      topics.push(item.topic)
    }
    return item
  })

  if (mqttServer === null) {
    mqttServer = new MqttServer([topics])
    console.log(mqttServer)
  }

  // 定义消息处理函数
  const handleMessage = message => {
    const data = {
      mete: message,
      topic: message.destinationName,
      data: {},
      metaData: {}
    }
    if (message.topic && message.topic.startsWith('Dev/')) {
      data.data = JSON.parse(message.payloadString)
    } else if (message.topic && message.topic.startsWith('RJ')) {
      const payload = JSON.parse(message.payloadString)
      const sj = payload.Data.value
      data.data = { sj }
      data.metaData = payload
    } else if ((message.topic && message.topic.startsWith('XH')) || (message.topic && message.topic.startsWith('JB'))) {
      const payload = JSON.parse(message.payloadString)
      const sj = payload.Data.value
      data.data = { sj }
      data.metaData = payload
      console.log('other message:', message)
    } else if (message.topic.startsWith('/SY-Dev')) {
      data.data = JSON.parse(message.payloadString)
      const { attribute, params } = data.data
      const [_, dev_name] = message.topic.split('/')
      const machineNumber = dev_name.split('Dev')[1] ? +dev_name.split('Dev')[1] : null
      console.log(machineNumber)
      if (!params) return
      const [firstItem] = params
      const { points } = firstItem
      let setRunTime = 0
      let currRunTime = 0
      if (machineNumber && machineNumber < 5) {
        const D146 = points.find(pointsItem => pointsItem.name === 'D146')?.value || 0 // 小时
        const D148 = points.find(pointsItem => pointsItem.name === 'D148')?.value || 0 // 分钟

        const C10 = points.find(pointsItem => pointsItem.name === 'C10')?.value || 0 // 秒
        const C11 = points.find(pointsItem => pointsItem.name === 'C11')?.value || 0 // 分钟
        const C12 = points.find(pointsItem => pointsItem.name === 'C12')?.value || 0 // 小时

        setRunTime = Number(D146) * 3600 + Number(D148) * 60
        currRunTime = Number(C12) * 3600 + Number(C11) * 60 + Number(C10)
      } else if ((machineNumber === 5) & (machineNumber === 6)) {
        const Set_Hour = points.find(pointsItem => pointsItem.name === 'Set_Hour')?.value || 0
        const Set_Min = points.find(pointsItem => pointsItem.name === 'Set_Min')?.value || 0

        const Run_Sec = points.find(pointsItem => pointsItem.name === 'Run_Sec')?.value || 0 // 秒
        const Run_Sec2 = points.find(pointsItem => pointsItem.name === 'Run_Sec2')?.value || 0 // 分钟
        const Run_Hour = points.find(pointsItem => pointsItem.name === 'Run_Hour')?.value || 0 // 小时

        console.log('machineNumber', Set_Hour, Set_Min, Run_Hour, Run_Sec2, Run_Sec)
        setRunTime = Number(Set_Hour) * 3600 + Number(Set_Min) * 60

        currRunTime = Number(Run_Hour) * 3600 + Number(Run_Sec2) * 60 + Number(Run_Sec)
      } else if (machineNumber >= 7) {
        const Set_Hour = points.find(pointsItem => pointsItem.name === 'Set_Hour')?.value || 0 // 设置小时
        const Set_Min = points.find(pointsItem => pointsItem.name === 'Set_Min')?.value || 0 // 设置分钟

        const Run_Min2 = points.find(pointsItem => pointsItem.name === 'Run_Min2')?.value || 0 // 分钟
        const Run_Sec2 = points.find(pointsItem => pointsItem.name === 'Run_Sec2')?.value || 0 // 秒

        setRunTime = Number(Set_Hour) * 3600 + Number(Set_Min) * 60
        currRunTime = Number(Run_Min2) * 60 + Number(Run_Sec2)
      }

      data.metaData.Data = {
        upload_name: '运行时间',
        value: currRunTime
      }

      console.log(machineNumber, currRunTime, setRunTime)
    } else if (message.topic.startsWith('JXHD')) {
      const payload = JSON.parse(message.payloadString)
      data.data = { sj: payload.msg.total_output }
      data.metaData = JSON.parse(message.payloadString)
    }
    toUpdateItem(data)
  }

  // 注册消息回调
  mqttServer.addMessageCallback(handleMessage)

  // 在组件卸载时移除回调
  onUnmounted(() => {
    socket.removeAllListeners('report-system-update')
    if (mqttServer) {
      mqttServer.removeMessageCallback(handleMessage)
    }
  })
}

const toUpdateItem = message => {
  let machine
  let sj
  if (message.topic.startsWith('Dev/')) {
    sj = Number(message.data.sj)
    machine = machineList.value.filter(item => item.topic === message.topic)
  } else if (message.topic.startsWith('RJ')) {
    const {
      metaData: { Data }
    } = message

    if (Data.upload_name === '产量') {
      sj = Number(message.data.sj)
      machine = machineList.value.filter(item => item.topic === message.topic && item.topicName == Data.device_name)
    }

    if (Data.upload_name === '运行时间') {
      machine = machineList.value.filter(item => item.topic === message.topic && item.topicName == Data.device_name)
      return
    }
  } else if (message.topic.startsWith('XH') || message.topic.startsWith('JB')) {
    const {
      metaData: { Data }
    } = message

    if (Data.upload_name === '产量') {
      sj = Number(message.data.sj)
      machine = machineList.value.filter(item => item.topic === message.topic && item.topicName == Data.device_name)
    }

    if (Data.upload_name === '运行时间') {
      machine = machineList.value.filter(item => item.topic === message.topic && item.topicName == Data.device_name)
      return
    }
  } else if (message.topic.startsWith('/SY-Dev')) {
    const {
      metaData: { Data }
    } = message

    if (Data.upload_name === '产量') {
      sj = Number(message.data.sj)
      machine = machineList.value.filter(item => item.topic === message.topic)
    }

    if (Data.upload_name === '运行时间') {
      machine = machineList.value.filter(item => item.topic === message.topic)
      return
    }
  } else if (message.topic.startsWith('JXHD')) {
    sj = Number(message.data.sj)
    console.log(message)
    machine = machineList.value.filter(
      item => item.topic === message.topic && item.topicName == message.metaData.deviceName
    )
  }

  if (machine) {
    machine.map(item => {
      item.oldValue = item.sj
      item.sj = sj || 0
      item.showTipicIcon = true
      setTimeout(() => {
        item.showTipicIcon = false
      }, 800)
    })
  }
}

defineExpose({ loadData })

onMounted(loadData)
</script>

<template>
  <div class="ps_w_h_100">
    <div class="left ps_h_100">
      <dv-border-box13 style="padding: 20px">
        <div style="height: 50%">
          <div class="board-title" style="color: #fff">数采设备状态</div>
          <div
            style="
              display: flex;
              gap: 10px;
              flex-wrap: wrap;
              justify-content: space-around;
              align-items: center;
              height: 100%;
              width: 100%;
              padding: 0 20px 0 20px;
            "
          >
            <template v-for="(item, index) in list" :key="index">
              <div v-if="!props.topic" style="align-items: center; text-align: center">
                <div style="display: flex; align-items: center">
                  <div
                    style="height: 10px; width: 10px; border-radius: 50%"
                    :style="{ backgroundColor: item.color, border: item.border }"
                  ></div>
                  <div style="color: #fff">{{ item.status }}</div>
                </div>
                <div style="color: aliceblue; font-size: 20px; font-weight: bolder" v-if="!props.topic">
                  {{ item.value }}
                </div>
              </div>
            </template>
          </div>
        </div>
        <div style="height: 50%; width: 100%">
          <productionBoard1v2></productionBoard1v2>
        </div>
      </dv-border-box13>
    </div>
  </div>
</template>

<style scoped lang="scss">
.ps-machine {
  display: grid;
  font-size: 14px;
  &-item {
    min-height: 135px;
    border-radius: 10px;
    padding: 26px 10px 0;
    border-width: 2px;
    border-style: solid;
    position: relative;
    overflow: hidden;
    color: #fff;
    // background-color: #fff;

    // 设备ID
    .machineID {
      position: absolute;
      top: 0;
      left: 0;
      color: #fff;
      padding: 4px 8px;
      border-bottom-right-radius: 10px;
    }

    .machineName {
      font-size: 18px;
      font-weight: bold;
      text-align: center;
      vertical-align: middle;
      margin-bottom: 5px;
      transition: all 0.5s;
      position: absolute;
      top: 0;
      left: 50%;
      transform: translateX(-50%);
    }

    .sfm {
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
    }

    .desc-item {
      line-height: 20px;

      .label {
        display: inline-block;
        // color: #909399;
        width: 4.5em;
      }
    }

    &.red {
      border-color: var(--cbs-machine-red);
    }

    &.blue {
      border-color: var(--cbs-machine-blue);
    }

    &.green {
      border-color: var(--cbs-machine-green);
    }
  }
}

:deep(.el-carousel) {
  height: 100%;
  .el-carousel__container {
    height: 100%;
  }
}
</style>
